package com.dmz.spring.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.dmz.spring.security.exception.VerifyCodeException;
import com.dmz.spring.security.handler.LoginFailureHandler;

/**
 * 验证码过滤器
 *
 * @author rico
 */
@Component
public class VerifyCodeFilter extends OncePerRequestFilter {

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().equals("/login") && request.getMethod().equalsIgnoreCase("post")) {
            try {
                validate(request);
            } catch (VerifyCodeException e) {
                loginFailureHandler.onAuthenticationFailure(request,response,e);
                return;
            }
        }
        // 检验通过，放行！
        filterChain.doFilter(request,response);
    }

    /**
     * 验证保存在session的验证码和表单提交的验证码是否一致
     *
     * @Author ZHANGCHAO
     * @Date 2020/3/13 11:30
     * @param
     * @param request
     * @retrun void
     **/
    private void validate(HttpServletRequest request) throws ServletRequestBindingException {
        String captcha = ServletRequestUtils.getStringParameter(request,"captcha");
        String code = (String) request.getSession().getAttribute(request.getParameter("uuid"));
        if (captcha==null||!captcha.equalsIgnoreCase(code)){
            throw new VerifyCodeException("验证码不正确！");
        }
        //清除session中的验证码
        request.getSession().removeAttribute(request.getParameter("uuid"));
    }
}
